package com.bawei.module_mine.ui

import android.util.Log
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.aop.LoginManager
import com.bawei.lib_common.mvi.base.BaseMVIActivity
import com.bawei.lib_net.datastore.DataStoreUtils
import com.bawei.module_mine.R
import com.bawei.module_mine.common.ConstanstValue
import com.bawei.module_mine.common.GsonUtil
import com.bawei.module_mine.databinding.ActivityLoginBinding
import com.bawei.module_mine.intent.LoginIntent
import com.bawei.module_mine.state.LoginState
import com.bawei.module_mine.viewmodel.LoginViewModel
import com.hyphenate.EMCallBack
import com.hyphenate.chat.EMClient
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch


@Route(path = "/module_mine/LoginActivity")
class LoginActivity : BaseMVIActivity() {

    lateinit var binding: ActivityLoginBinding
    var viewModel: LoginViewModel? = null

    override fun generatStatusBarColor(): Int {
        return R.color.colorPrimary
    }

    override fun initData() {
        super.initData()
        requestPermission()
    }

    override fun generateViewModel() {
        viewModel = LoginViewModel()
    }

    override fun getLayoutRootView(): View {
        Log.e("LoginActivity", "getLayoutRootView called")
        binding = ActivityLoginBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        super.initView()
        Log.e("LoginActivity", "initView called")
    }

    override fun onDestroy() {
        super.onDestroy()
        // 通知LoginManager登录页面已关闭
        LoginManager.onLoginPageClosed()
        Log.d("LoginActivity", "登录页面已关闭")
    }

    override fun onBackPressed() {
        Log.d("LoginActivity", "用户点击返回键")
        // 确保在返回时也清理状态
        LoginManager.onLoginPageClosed()
        super.onBackPressed()
    }

    override fun handleState() {
        lifecycleScope.launch {
            viewModel?.state?.collect { state ->
                when (state) {
                    is LoginState.loginSuccess -> {
                        try {
                            if (state.result != null) {
                                Log.d("LoginActivity", "登录成功，保存用户信息")

                                //环信登陆
                                EMClient.getInstance().login(
                                    state.result.username,
                                    state.result.password,
                                    object : EMCallBack {
                                        // 登录成功回调
                                        override fun onSuccess() {
                                        }

                                        // 登录失败回调，包含错误信息
                                        override fun onError(code: Int, error: String) {
                                        }
                                    })

                                // 检查token是否为空
                                val token = state.result.token
                                if (token.isNullOrEmpty()) {
                                    Log.e("LoginActivity", "登录成功但token为空")
                                    showMsg("登录成功但token异常，请重试")
                                    // 恢复按钮状态
                                    binding.btnLogin.isEnabled = true
                                    binding.btnLogin.text = "登录"
                                    return@collect
                                }

                              
                                //MMKV.defaultMMKV().encode("userId",state.result.id)
                                LoginManager.onLoginSuccess(token)
                                MMKV.defaultMMKV().encode("account", state.result.username)
                                MMKV.defaultMMKV().encode("password", state.result.password)
                                // 保存用户id到MMKV
                                MMKV.defaultMMKV().encode("userId", state.result.id.toString())
                                Log.d("FollowDebug", "登录成功后写入userId: ${state.result.id}")
                                val testUserId = MMKV.defaultMMKV().decodeString("userId") ?: ""
                                Log.d("FollowDebug", "登录后MMKV userId=$testUserId")

                                // 安全地保存用户信息
                                try {
                                    DataStoreUtils.putData(
                                        ConstanstValue.CURRENT_USER,
                                        GsonUtil.toJsonWtihNullField(state.result)
                                    )
                                    DataStoreUtils.putData(ConstanstValue.TOKEN, token)
                                } catch (e: Exception) {
                                    Log.e("LoginActivity", "保存用户信息失败: ${e.message}", e)
                                    // 即使保存失败，也要保存token
                                    DataStoreUtils.putData(ConstanstValue.TOKEN, token)
                                }

                                showMsg("登录成功")
                                closeThis()
                            } else {
                                Log.e("LoginActivity", "登录成功但用户信息为空")
                                showMsg("登录成功但用户信息异常")
                                // 恢复按钮状态
                                binding.btnLogin.isEnabled = true
                                binding.btnLogin.text = "登录"
                            }
                        } catch (e: Exception) {
                            Log.e("LoginActivity", "处理登录成功状态异常: ${e.message}", e)
                            showMsg("登录成功但保存信息失败")
                            // 恢复按钮状态
                            binding.btnLogin.isEnabled = true
                            binding.btnLogin.text = "登录"
                        }
                    }

                    is LoginState.loginFailed -> {
                        try {
                            Log.d("LoginActivity", "登录失败")
                            showMsg("用户名或密码错误，请重试")
                            // 恢复按钮状态
                            binding.btnLogin.isEnabled = true
                            binding.btnLogin.text = "登录"
                        } catch (e: Exception) {
                            Log.e("LoginActivity", "处理登录失败状态异常: ${e.message}", e)
                            showMsg("登录失败，请重试")
                            // 恢复按钮状态
                            binding.btnLogin.isEnabled = true
                            binding.btnLogin.text = "登录"
                        }
                    }

                    is LoginState.loginInit -> {
                        Log.d("LoginActivity", "登录状态初始化")
                        // 确保按钮状态正常
                        binding.btnLogin.isEnabled = true
                        binding.btnLogin.text = "登录"
                    }
                }
            }
        }
    }

    private fun requestPermission() {

    }

    override fun initEvent() {
        super.initEvent()
        Log.e("LoginActivity", "initEvent called")
        binding.btnLogin.setOnClickListener {
            try {
                Log.e("LoginActivity", "btnLogin clicked")
                val username: String = binding.etPhone.text.trim().toString()
                val pwd: String = binding.etPassword.text.trim().toString()

                if (username.isEmpty()) {
                    showMsg("请输入用户名")
                    return@setOnClickListener
                }
                if (pwd.isEmpty()) {
                    showMsg("请输入密码")
                    return@setOnClickListener
                }

                // 显示加载状态
                binding.btnLogin.isEnabled = false
                binding.btnLogin.text = "登录中..."

                lifecycleScope.launch {
                    try {
                        Log.e("LoginActivity", "send LoginIntent.Login")
                        viewModel?.intents?.send(LoginIntent.Login(username, pwd))
                    } catch (e: Exception) {
                        Log.e("LoginActivity", "发送登录请求异常: ${e.message}", e)
                        showMsg("登录请求失败，请重试")
                        // 恢复按钮状态
                        binding.btnLogin.isEnabled = true
                        binding.btnLogin.text = "登录"
                    }
                }
            } catch (e: Exception) {
                Log.e("LoginActivity", "登录按钮点击异常: ${e.message}", e)
                showMsg("操作异常，请重试")
                // 恢复按钮状态
                binding.btnLogin.isEnabled = true
                binding.btnLogin.text = "登录"
            }
        }
        binding.tvForgetPwd.setOnClickListener {
            Log.e("LoginActivity", "tvForgetPwd clicked")
            ARouter.getInstance().build("/module_mine/ForgetPwdActivity")
                .withTransition(R.anim.slide_in_from_right, R.anim.slide_out_from_left)
                .navigation()
        }
        binding.tvRegister.setOnClickListener {
            Log.e("LoginActivity", "tvRegister clicked")
            ARouter.getInstance().build("/module_mine/RegActivity")
                .withTransition(R.anim.slide_in_from_right, R.anim.slide_out_from_left)
                .navigation()
        }
        binding.btnBack.setOnClickListener {
            onBackPressed()
        }
    }

}